#ifndef XDEVICE_RPC_H
#define XDEVICE_RPC_H

#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/* RPC message types */
typedef enum {
    XDEVICE_RPC_GET_STATUS = 1,
    XDEVICE_RPC_GET_CLUSTER_INFO = 2,
    XDEVICE_RPC_GET_RAFT_LOG = 3,
    XDEVICE_RPC_GET_DEVICES = 4,
    XDEVICE_RPC_PING = 5
} xdevice_rpc_message_type_t;

/* RPC message structure */
typedef struct {
    uint32_t type;
    uint32_t request_id;
    uint32_t data_length;
    char data[0];  // Variable length data
} xdevice_rpc_message_t;

/* RPC response codes */
typedef enum {
    XDEVICE_RPC_OK = 0,
    XDEVICE_RPC_ERROR = -1,
    XDEVICE_RPC_INVALID_REQUEST = -2,
    XDEVICE_RPC_TIMEOUT = -3
} xdevice_rpc_result_t;

/* Node status structure for RPC */
typedef struct {
    int node_id;
    int state;  // 0=follower, 1=candidate, 2=leader
    uint64_t current_term;
    uint64_t commit_index;
    uint64_t last_applied;
    uint64_t last_log_index;
    uint64_t last_log_term;
    int leader_id;
    bool is_healthy;
    uint64_t election_timeout_ms;
    uint64_t heartbeat_interval_ms;
    uint64_t last_heartbeat_time;
} xdevice_rpc_node_status_t;

/* Cluster status for RPC */
typedef struct {
    int node_count;
    int active_nodes;
    int leader_id;
    uint64_t cluster_term;
    bool cluster_healthy;
    xdevice_rpc_node_status_t nodes[16];  // Max 16 nodes
} xdevice_rpc_cluster_status_t;

/* Log entries info for RPC */
typedef struct {
    uint64_t start_index;
    uint64_t end_index;
    uint64_t commit_index;
    uint32_t entry_count;
    struct {
        uint64_t index;
        uint64_t term;
        uint32_t type;
        uint32_t data_size;
        char data_preview[64];  // First 64 bytes of data
    } entries[10];  // Show up to 10 recent entries
} xdevice_rpc_log_info_t;

/* Device list for RPC */
typedef struct {
    int device_count;
    struct {
        char name[128];
        uint64_t size;
        int state;
        int storage_type;
        bool readonly;
    } devices[32];  // Max 32 devices
} xdevice_rpc_device_list_t;

/* RPC Server functions */
int xdevice_rpc_server_start(const char* socket_path);
void xdevice_rpc_server_stop(void);
int xdevice_rpc_server_set_context(void* xdevice_ctx);

/* RPC Client functions */
int xdevice_rpc_client_connect(const char* socket_path);
void xdevice_rpc_client_disconnect(int client_fd);

int xdevice_rpc_get_node_status(int client_fd, xdevice_rpc_node_status_t* status);
int xdevice_rpc_get_cluster_status(int client_fd, xdevice_rpc_cluster_status_t* status);
int xdevice_rpc_get_log_info(int client_fd, xdevice_rpc_log_info_t* log_info);
int xdevice_rpc_get_device_list(int client_fd, xdevice_rpc_device_list_t* device_list);
int xdevice_rpc_ping(int client_fd);

#ifdef __cplusplus
}
#endif

#endif /* XDEVICE_RPC_H */
